package common

import (
	"fmt"
	"math/rand"
	"os"
	"time"

	"git.edaijia-inc.cn/edaijia/ego/elogger"
	"git.edaijia-inc.cn/edaijia/ego/emysql"
	"git.edaijia-inc.cn/edaijia/ego/eredis"

	"github.com/go-ini/ini"
)

type GlobalConfig struct {
	Env      string `ini:"-"`
	Service  string `ini:"service"`
	HttpAddr string `ini:"httpaddr"`
	Log      *elogger.ELoggerConfig
	Redis    *eredis.ERedisConfig
	Mysql    *emysql.EMysqlConfig
}

var gConfig *GlobalConfig = &GlobalConfig{
	HttpAddr: "127.0.0.1:8888",
	Log: &elogger.ELoggerConfig{
		Path:       "./logs",
		Level:      "info",
		FilePrefix: "app",
		Console:    false,
	},
	Redis: &eredis.ERedisConfig{},
	Mysql: &emysql.EMysqlConfig{},
}

func InitConfig() *GlobalConfig {
	if len(os.Args) < 2 {
		panic("usage: bin config.ini")
	}

	cfg, err := ini.Load(os.Args[1])
	if err != nil {
		fmt.Printf("Fail to read file: %v\n", err)
		os.Exit(1)
	}

	gConfig.Env = cfg.Section("").Key("env").String()
	if gConfig.Env == "" {
		fmt.Printf("miss env in config file")
		os.Exit(1)
	}
	gConfig.HttpAddr = cfg.Section("").Key("httpaddr").String()
	gConfig.Service = cfg.Section("").Key("service").String()

	err = cfg.Section(gConfig.Env + ".log").MapTo(gConfig.Log)
	if err != nil {
		fmt.Printf("Fail to read config file: %v\n", err)
		os.Exit(1)
	}

	err = cfg.Section(gConfig.Env + ".redis").MapTo(gConfig.Redis)
	if err != nil {
		fmt.Printf("Fail to read config file: %v\n", err)
		os.Exit(1)
	}

	err = cfg.Section(gConfig.Env + ".mysql").MapTo(gConfig.Mysql)
	if err != nil {
		fmt.Printf("Fail to read config file: %v\n", err)
		os.Exit(1)
	}

	rand.Seed(time.Now().UnixNano())

	//check your config here

	return gConfig
}

func GetGConfig() *GlobalConfig {
	return gConfig
}

func IsProd() bool {
	return gConfig.Env == "prod"
}
